package com.hz.us.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hz.us.helper.UserHelper;
import com.hz.us.mapper.ClassMapper;
import com.hz.us.mapper.GradeMapper;
import com.hz.us.mapper.UserMapper;
import com.hz.us.model.entity.ClassEntity;
import com.hz.us.model.entity.GradeEntity;
import com.hz.us.model.entity.UserEntity;
import com.hz.us.model.enums.UserTypeEnum;
import com.hz.us.service.UserManagerService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserManagerServiceImpl implements UserManagerService {

    @Resource
    GradeMapper gradeMapper;

    @Resource
    ClassMapper classMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public int addGrade(String gradeName, String gradeYear) {

        if (gradeMapper.selectByGradename(gradeName) != null) {
            // 如果年级名称重复则不能添加
            return 0;
        } else {
            GradeEntity gradeEntity = new GradeEntity();
            gradeEntity.setGrade_name(gradeName);
            gradeEntity.setGrade_year(gradeYear);
            return gradeMapper.addGrade(gradeEntity);
        }


    }

    @Override
    public int addClass(String className, Integer gradeId) {
        // 是否有传入的年级
        GradeEntity gradeEntity = gradeMapper.selectById(gradeId);
        if (gradeEntity == null) {
            return 0;
        }
        // 是否有重名的班级
        ClassEntity classEntity = classMapper.selectByName(className);
        if (classEntity != null) {
            return 0;
        }

        ClassEntity newClass = new ClassEntity();
        newClass.setClass_name(className);
        newClass.setGrade_id(gradeId);
        newClass.setGrade_name(gradeEntity.getGrade_name());
        newClass.setGrade_year(gradeEntity.getGrade_year());
        return classMapper.addClass(newClass);
    }

    @Override
    public int addManager(String username, String realname, String password) {
        UserEntity userEntity = userMapper.selectByUsernameAndUsertype(username, UserTypeEnum.MANAGER.getUserType());
        if (userEntity != null) {
            return 0;
        }
        UserEntity newManager = new UserEntity();
        newManager.setUsername(username);
        newManager.setRealname(realname);
        newManager.setUser_type(UserTypeEnum.MANAGER.getUserType());
        // 生成密码
        String salt = UUID.randomUUID().toString();
        String pwd = UserHelper.createNewPwd(password, salt);
        newManager.setPwd(pwd);
        newManager.setPwd_salt(salt);
        // 密码有效期 7 天
        newManager.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
        return userMapper.addUser(newManager);
    }

    @Override
    public int addTeacher(String username, String realname, String password, String schoolId) {
        UserEntity userEntity = userMapper.selectByUsernameAndUsertype(username, UserTypeEnum.TEACHER.getUserType());
        if (userEntity != null) {
            return 0;
        }
        UserEntity newTeacher = new UserEntity();
        newTeacher.setUsername(username);
        newTeacher.setRealname(realname);
        newTeacher.setUser_type(UserTypeEnum.TEACHER.getUserType());
        newTeacher.setStudent_id(schoolId);
        // 生成密码
        String salt = UUID.randomUUID().toString();
        String pwd = UserHelper.createNewPwd(password, salt);
        newTeacher.setPwd(pwd);
        newTeacher.setPwd_salt(salt);
        // 密码有效期 7 天
        newTeacher.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
        return userMapper.addUser(newTeacher);
    }

    @Override
    public int addStudent(String username, String realname, String password, String studentId, Integer gradeId, Integer classId) {
        UserEntity userEntity = userMapper.selectByUsernameAndUsertype(username, UserTypeEnum.STUDENT.getUserType());
        if (userEntity != null) {
            return 0;
        }
        UserEntity newStudent = new UserEntity();
        newStudent.setUsername(username);
        newStudent.setRealname(realname);
        newStudent.setUser_type(UserTypeEnum.STUDENT.getUserType());
        newStudent.setStudent_id(studentId);
        // 生成密码
        String salt = UUID.randomUUID().toString();
        String pwd = UserHelper.createNewPwd(password, salt);
        newStudent.setPwd(pwd);
        newStudent.setPwd_salt(salt);
        // 密码有效期 7 天
        newStudent.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
        newStudent.setGrade_id(gradeId);
        newStudent.setClass_id(classId);

        return userMapper.addUser(newStudent);
    }

    @Override
    public String login(String username, String password, Integer userType) {
        UserEntity userEntity = userMapper.selectByUsernameAndUsertype(username, userType);
        if (userEntity == null) {
            return null;
        }
        String encryptedPassword = UserHelper.createNewPwd(password, userEntity.getPwd_salt());
        if (!encryptedPassword.equals(userEntity.getPwd())) {
            return null;
        }

        // 登录成功保存到REDIS
        redisTemplate.opsForValue().set(username, JSON.toJSONString(userEntity), 30, TimeUnit.MINUTES);
        return JSON.toJSONString(userEntity);
    }

    @Override
    public int logout(String username) {
        redisTemplate.delete(username);
        return 1;
    }

    @Override
    public int changePwd(Integer userId, String originPwd, String newPassword) {
        UserEntity userEntity = userMapper.selectById(userId);
        String pwd = userEntity.getPwd();
        String pwdSalt = userEntity.getPwd_salt();
        if (!pwd.equals(UserHelper.createNewPwd(originPwd, pwdSalt))) {
            // 原密码错误，不能修改
            return 0;
        }
        String newPwd = UserHelper.createNewPwd(newPassword, pwdSalt);
        if (pwd.equals(newPwd)) {
            // 新密码和原密码相同，不能修改
            return 0;
        }
        if (userMapper.updatePwd(userId, newPwd, System.currentTimeMillis() + 7 * 24 * 3600 * 1000) > 0) {
            redisTemplate.delete(userEntity.getUsername());
            return 1;
        } else {
            return 0;
        }
    }
}
